import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from "@/views/Login";
import Home from "@/views/Home";
import store from "@/store";
import {initMenu} from "@/utils/menus";
import {getRequest} from "@/utils/api";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        name: 'Login',
        component: Login,
        meta: {hidden: true}
    },
    {
        path: '/home',
        name: '导航一',
        component: Home,
    },
]

const router = new VueRouter({
    routes
})

router.beforeEach((to, from, next) => {
    if (to.path === '/') {
        next()
    }
    if (localStorage.getItem('tokenStr')) {
        initMenu(router, store); // 暂定菜单数据永远比用户信息慢
        if (!sessionStorage.getItem('userInfo')) {
            return getRequest('/login/admin').then(res => {
                if (res) {
                    // 存入用户信息
                    sessionStorage.setItem('userInfo', JSON.stringify(res))
                    next(to.path)  // next() 好像逻辑问题跳不了
                }
            })
        }
        next();
    } else {
        next('/')
    }
})
export default router
